package hsh.machine.components;

import java.util.ArrayList;
import java.util.List;

import hsh.machine.instructions.Instruction;

public class PrimaryMemory {

	private int sizeInInstructions;
	private Instruction[] memoryInstructions;
	private Bus bus;
	
	
	public PrimaryMemory(int sizeInInstructions,Bus bus) {
		super();
		this.sizeInInstructions = sizeInInstructions;
	}

	public void storeInstructions(int startPosition,List<Instruction> instructions) throws Exception{
		
		if(startPosition + instructions.size() > sizeInInstructions){
			throw new Exception("Out of Memory");
		}
		
		for(int i = startPosition; i < instructions.size();i++){
			memoryInstructions[i] = instructions.get(i);
		}
	}
	
	public void storeInstruction(int position,Instruction instructions) throws Exception{
		
		if(position >= sizeInInstructions){
			throw new Exception("Out of Memory");
		}
		
		memoryInstructions[position] = instructions;		
	}
	
	public List<Instruction> loadInstructions(int startPosition,int quantity) throws Exception{
		
		ArrayList<Instruction> instructions;
		
		if(startPosition + quantity > sizeInInstructions){
			throw new Exception("Out of Memory");
		}
		
		instructions =  new ArrayList<Instruction>(quantity);
		
		for(int i = startPosition; i < quantity; i++){
			instructions.add(memoryInstructions[i]);
		}
		
		return instructions;
	}
	
	public Instruction loadInstruction(int position) throws Exception{
		
		if(position >= sizeInInstructions){
			throw new Exception("Out of Memory");
		}
		
		return memoryInstructions[position];		
	}

	
	public int getSize(){
		return sizeInInstructions;
	}
}
